﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Threading;
using App.Business.Entities.Party;
using App.Business.Party;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RrslLite.Configuration;
using RrslLite.Dsl;
using RrslLite.Net.Attributes;

namespace App.Test.RrslLiteTEST
{
	[TestClass]
	public class LogExceptionsTEST
	{
		private NamedPipeClientStream pipeStream;

		[TestInitialize]
		public void Init()
		{
			KnownTypeProvider.RegisterModelDomainNamespace("App.Business.Entities");
			pipeStream = new NamedPipeClientStream("testpipe-WcfMessageWervice");
		}

		[TestMethodAttribute]
		public void LogAsyncMessageException()
		{
			IBatchBuilder factory = RrslLiteConfiguration.Instance.BatchBuilderConfiguration.GetAsyncBatchBuilder();
			var @eventCall1 = new ManualResetEvent(false);

			bool exceptionCommandCompletedIsExecuted = false;
			bool okCommandCompletedIsExecuted = false;
			bool wasThrownOneException = false;

			factory
				.Call<ITestExceptionService>()
				.WithCommand(f => f.GetCompaniesException(5), () => { exceptionCommandCompletedIsExecuted = true; })
				.WithCommand(f => f.GetCompaniesOk(), () => { okCommandCompletedIsExecuted = true; })
				.WhenCompleted(
					batches =>
					{
						Assert.AreEqual(batches.Count(), 2);
						wasThrownOneException = batches.Count(e => e.WasExceptionThrown) == 1;
						@eventCall1.Set();
					}
				)
				.Execute();

			pipeStream.Connect();
			pipeStream.ReadMode = PipeTransmissionMode.Message;

			Byte[] bytes = new Byte[ExceptionConstants.MessageFromServer.Length];

			Assert.IsTrue(pipeStream.IsConnected);

			pipeStream.Read(bytes, 0, bytes.Length);
			string message = Encoding.ASCII.GetString(bytes);

			Assert.AreEqual(0,pipeStream.Read(bytes, 0, bytes.Length));
			Assert.AreEqual(message, ExceptionConstants.MessageFromServer);

			@eventCall1.WaitOne();

			Assert.IsFalse(exceptionCommandCompletedIsExecuted);
			Assert.IsTrue(okCommandCompletedIsExecuted);
			Assert.IsTrue(wasThrownOneException);
		}

		

	}
}